package com.truthbean.jeetb.utils.web;

import java.io.*;

public class OnLineConnector extends Thread {
    private OnLineProcess ol = null;
    private InputStream is;
    private OutputStream os;
    private String name;

    public OnLineConnector(InputStream is, OutputStream os, String name, OnLineProcess ol) {
        this.is = is;
        this.os = os;
        this.name = name;
        this.ol = ol;
    }

    public void run() {
        BufferedReader in = null;
        BufferedWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.is));
            out = new BufferedWriter(new OutputStreamWriter(this.os));
            char buffer[] = new char[128];
            if (this.name.equals("exeRclientO")) {
                //from exe to client
                int length = 0;
                while ((length = in.read(buffer, 0, buffer.length)) > 0) {
                    String str = new String(buffer, 0, length);
                    str = str.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
                    str = str.replace("" + (char) 13 + (char) 10, "<br/>");
                    str = str.replace("\n", "<br/>");
                    out.write(str.toCharArray(), 0, str.length());
                    out.flush();
                }
            } else {
                //from client to exe
                while (true) {
                    while (this.ol.getCmd() == null) {
                        Thread.sleep(500);
                    }
                    if (this.ol.getCmd().equals("first")) {
                        this.ol.setCmd(null);
                        continue;
                    }
                    this.ol.setCmd(this.ol.getCmd() + (char) 10);
                    char[] arr = this.ol.getCmd().toCharArray();
                    out.write(arr, 0, arr.length);
                    out.flush();
                    this.ol.setCmd(null);
                }
            }
        } catch (Exception e) {
        }
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (Exception e) {
            System.err.print(e.getMessage());
        }
    }
}